import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: 'http://43.139.168.148:8080/api',
  timeout: 2000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
})

// 请求拦截器
request.interceptors.request.use(request => {
  const token = localStorage.getItem('token') ?? ''
  request.headers.Authorization = `Bearer ${token}`
  return request
})

// 响应拦截器
request.interceptors.response.use(response => {
  if (response.status === 401) {
    ElMessage.error(response.data?.msg ?? '登录信息过期，请重新登录')
    throw new Error('登录信息过期，请重新登录')
  } else if (response.data?.code !== 200) {
    ElMessage.error(response.data?.msg ?? '请求失败')
    throw new Error(response.data?.msg ?? '请求失败')
  }
  return response.data
})

export { request }
